<template>
  <el-card shadow="never">
    <el-button type="primary" class="add-cate" @click="cateFormVisible = true">添加分类</el-button>
  </el-card>

  <el-table :data="tableData" border row-key="cat_id" lazy class="=categories" style="width: 100%">
    <el-table-column type="index" label="#" width="50" />
    <el-table-column prop="cat_name" label="分类名称" />
    <el-table-column prop="cat_delete" label="是否有效">
      <template #default="slot1">
        <CheckCircleFilled v-if="!slot1.row.cat_delete" style="color: green;"></CheckCircleFilled>
        <CloseCircleFilled v-else style="color: red;"></CloseCircleFilled>
      </template>
    </el-table-column>
    <el-table-column prop="cat_level" label="排序">
      <template #default="slot2">
        <el-tag v-if="slot2.row.cat_level === 0" size="small">一级</el-tag>
        <el-tag type="success" v-else-if="slot2.row.cat_level === 1" size="small">二级</el-tag>
        <el-tag type="warning" v-else size="small">三级</el-tag>
      </template>
    </el-table-column>
    <el-table-column label="操作">
      <template mplate #default="slot3">
        <el-button type="primary" :icon="EditOutlined" size="small" @click="editCategory(slot3.row)">编辑</el-button>
        <el-button type="danger" :icon="DeleteOutlined" size="small" @click="close(slot3.row.cat_id)">删除</el-button>
      </template>
    </el-table-column>
  </el-table>
  <ElConfigProvider :locale="zhCn">
    <el-pagination v-model:currentPage="currentPage" v-model:page-size="pageSize" :page-sizes="[5, 10, 20, 30]"
      layout="total,sizes,prev, pager, next,jumper" :total="total" @size-change="handleSizeChange"
      @current-change="handleCurrentChange" />

  </ElConfigProvider>


  <!-- 添加分类对话框 -->
  <el-dialog v-model="cateFormVisible" title="添加分类" @close="closeCateDialog">
    <el-form :model="cateForm" :rules="rules" ref="cateFormRef">
      <el-form-item label="分类名称" :label-width="formLabelWidth" prop="cat_name">
        <el-input v-model="cateForm.cat_name" autocomplete="off" />
      </el-form-item>
      <el-form-item label="父级分类" :label-width="formLabelWidth">
        <!-- <el-input v-model="cateForm.cat_info" autocomplete="off" /> -->
        <el-cascader v-model="cateForm.cat_info" :options="options"
          :props="{ value: 'cat_id', label: 'cat_name', children: 'children' }" @change="handleChange" :clearable="true"
          :teleported="false">
        </el-cascader>
      </el-form-item>
    </el-form>
    <template #footer>
      <span>
        <el-button type="primary" @click="submitForm(cateFormRef)">提交</el-button>
        <el-button @click="resetForm(cateFormRef)">
          重置
        </el-button>
      </span>
    </template>
  </el-dialog>

  <!-- 编辑对话框 -->
  <el-dialog v-model="editdialogFormVisible" title="编辑分类">
    <el-form :model="EditcateForm" :rules="rules" ref="ruleEditFormRef">
      <el-form-item label="分类名称" :label-width="formLabelWidth" prop="cat_name">
        <el-input v-model="EditcateForm.cat_name" autocomplete="off" />
      </el-form-item>

    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button type="primary" @click="submitEditForm(ruleEditFormRef)">提交</el-button>
        <el-button @click="resetEditForm(ruleEditFormRef)">
          重置
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { ElMessage } from 'element-plus'
import zhCn from 'element-plus/lib/locale/lang/zh-cn'
import { ElConfigProvider } from 'element-plus'
import { ref, onBeforeMount, reactive } from 'vue'
import axios from '../../axios'
import { CheckCircleFilled, CloseCircleFilled, DeleteOutlined, EditOutlined } from '@ant-design/icons-vue';
const tableHeader = { background: '#9f9f9f' }
const tableData = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
onBeforeMount(async () => {
  const { data: res } = await axios.get(`categories`);
  if (res.meta.status == 200) return tableData.value = res.data
})

const getCategories = async () => {
  const { data: res } = await axios.get(`categories?pagenum=${currentPage.value}&pagesize=${pageSize.value}`)
  console.log(res);
  if (res.meta.status != 200) return
  tableData.value = res.data.result;
  total.value = res.data.total;
}

onBeforeMount(() => {
  getCategories();
  getParentList();
})

const handleSizeChange = (val) => {
  pageSize.value = val
  getCategories();
}
const handleCurrentChange = (val) => {
  currentPage.value = val
  getCategories();
}

const formLabelWidth = '140px'
const cateFormVisible = ref(false)
const cateFormRef = ref()
const cateForm = reactive({
  cat_name: '',
  cat_info: []
})
const rules = reactive({
  cat_name: [
    { required: true, message: '请输入分类名称', trigger: 'blur' },
  ],
})

const resetForm = (formEL) => {
  if (!formEL) return
  formEL.resetFields();
}

const handleChange = (value) => {
  console.log(value)
}

const options = ref([])
const getParentList = async () => {
  const { data: res } = await axios.get(`categories?type=2`)
  if (res.meta.status != 200) return
  options.value = res.data
}

const submitForm = async (formEl) => {
  if (!formEl) return
  await formEl.validate(async (valid) => {
    if (valid) {
      let cat_pid = 0
      let length = cateForm.cat_info.length
      if (length != 0) cat_pid = cateForm.cat_info[length - 1]
      const { data: res } = await axios.post(`categories`, {
        cat_pid: cat_pid,
        cat_name: cateForm.cat_name,
        cat_level: length
      })
      if (res.meta.status != 201) return ElMessage.error('添加分类失败')
      ElMessage.success("添加分类成功")
      getCategories()
      getParentList()
      cateFormVisible.value = false
    }
  })
}
const closeCateDialog = () => {
  cateForm.cat_name = ''
  cateForm.cat_info = [];
}

const ruleEditFormRef = ref(null)
const editdialogFormVisible = ref(false);
const EditcateForm = reactive({
  cat_name: '',
  cat_id: '',
})
const editCategory = (user) => {
  editdialogFormVisible.value = true;
  EditcateForm.cat_name = user.cat_name
  EditcateForm.cat_id = user.cat_id
}
const submitEditForm = async (formEL) => {
  if (!formEL) return
  await formEL.validate(async (valid, fields) => {
    if (valid) {
      const { data: res } = await axios.put(`/categories/${EditcateForm.cat_id}`,{
        cat_name: EditcateForm.cat_name,
        })
      console.log(res);
      getCategories()
      editdialogFormVisible.value = false
      ElMessage.success("修改成功")
    } else {
      console.log('error submit!', fields);
    }
  })
}

const resetEditForm = (formEL) => {
  if(!formEL)return
  formEL.resetFields()
}

const close = async (id) => {
  await axios.delete(`categories/${id}`);
  getCategories();
}
</script>

<style>
.add-cate {
  margin-bottom: 15px;
}
</style>